package edu.localisationPhone;

import java.util.ArrayList;
import java.util.StringTokenizer;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.telephony.SmsManager;
import android.telephony.SmsMessage;

import com.google.android.maps.GeoPoint;

public class GestionSMS extends BroadcastReceiver {

	private SauveteurActivity s;
	private RandonneurActivity r;

	public GestionSMS(SauveteurActivity sa) {
		super();
		setS(sa);
	}
	
	public GestionSMS(RandonneurActivity ra) {
		super();
		setR(ra);
	}

	@Override
	public void onReceive(Context context, Intent intent) {

		if (intent.getAction()
				.equals("android.provider.Telephony.SMS_RECEIVED")) {

			Bundle b = intent.getExtras();

			if (b != null) {
				Object[] pdus = (Object[]) b.get("pdus");
				SmsMessage[] messages = new SmsMessage[pdus.length];

				for (int i = 0; i < pdus.length; i++) {
					messages[i] = SmsMessage.createFromPdu((byte[]) pdus[i]);
				}
				for (SmsMessage message : messages) {
					String m = message.getMessageBody();
					String n = message.getOriginatingAddress();
					if (m.startsWith("wru")) {
						sendSMS(n, "Position Report:" + this.s.latitude + "," + this.s.longitude);
					} else if (m.startsWith("Position Report:")) {
						StringTokenizer st = new StringTokenizer(m, ":");
						ArrayList<String> liste = new ArrayList<String>();
						while (st.hasMoreTokens()) {
							liste.add(st.nextToken());
						}

						st = new StringTokenizer(liste.get(1), ",");
						ArrayList<String> liste2 = new ArrayList<String>();
						while (st.hasMoreTokens()) {
							liste2.add(st.nextToken());
						}

						GeoPoint point = new GeoPoint((int) (Double.parseDouble(liste2.get(0)) * 1e6), (int) (Double.parseDouble(liste2.get(1)) * 1e6));
						this.s.mv.getController().setZoom(14);
						this.s.mv.getController().setCenter(point);
					}
				}
			}

		}

	}

	public void sendSMS(String numero, String message) {
		SmsManager sm = SmsManager.getDefault();
		sm.sendTextMessage(numero, null, message, null, null);
	}

	public void setS(SauveteurActivity s) {
		this.s = s;
	}

	public SauveteurActivity getS() {
		return s;
	}

	public void setR(RandonneurActivity r) {
		this.r = r;
	}

	public RandonneurActivity getR() {
		return r;
	}

}
